package com.ma.security;

import com.ma.common.exception.CaptchaException;
import com.ma.common.lang.Const;
import com.ma.utils.RedisUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
    图片验证码校验过滤器，在登录过滤器前
    OncePerRequestFilter顾名思义，他能够确保在一次请求只通过一次filter，而不需要重复执行。
 */
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    private final String loginurl="/login";
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //通过请求路径和方式判断是否进行登录
        String url=request.getRequestURI();
        String method = request.getMethod();

        if (url.equals(loginurl) && method.equals("POST")){
            log.info("获取到login链接，正在校验验证码 -- " + url);
            try {
                validate(request);
            }catch (CaptchaException e){
                log.info(e.getMessage());
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
        filterChain.doFilter(request,response);
    }

    //验证码校验
    private void validate(HttpServletRequest request) {
        String token = request.getParameter("token");
        String code = request.getParameter("code");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(token)){
            throw new CaptchaException("验证码不能为空");
        }
        if (!code.equals(redisUtil.hget(Const.captcha_KEY,token))){
            throw new CaptchaException("验证码错误");
        }
        //验证码的一次性使用
        redisUtil.hdel(Const.captcha_KEY,token);
    }
}
